package com.example.jwtdemo.interceptor;

import com.example.core.libs.AppException;
import com.example.core.utils.JwtUtils;
import com.example.core.utils.RedisUtil;
import com.example.jwtdemo.annotation.Login;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisUtil redisUtil;

    public static final String USER_KEY = "userId";
    public static final String USER_ENTITY_KEY = "userEntity";
    public static final String USER_REDIS_LOGIN = "USER_REDIS_LOGIN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        // 判断是否属于方法。如果是方法，获取方法上的Login注解
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader("Authorization");
        Claims claims = jwtUtils.getClaimByToken(token);//解密
        if (claims == null) {
            throw new AppException(HttpStatus.UNAUTHORIZED.value(), "登录过期，请重新登录");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        String userId = String.valueOf(claims.getSubject());

        //redis防止重复登录
        Object tokenObj = redisUtil.hmGet(USER_REDIS_LOGIN, userId);
        if (tokenObj == null || !StringUtils.equals(token, String.valueOf(tokenObj))) {
            throw new AppException(HttpStatus.UNAUTHORIZED.value(), "登录过期，请重新登录");
        }

        request.setAttribute(USER_KEY, userId);
        request.setAttribute(USER_ENTITY_KEY, tokenObj);

        return true;
    }
}
